package com.chinasoft.back.mvc.interceptor;

import com.chinasoft.back.exception.BussinessException;
import com.chinasoft.back.exception.ExType;
import com.chinasoft.back.pojo.User;
import com.chinasoft.back.service.UserService;
import com.chinasoft.back.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 中软zhang
 * @create 2023-08-29 8:47
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("in token interceptor");
        // 如果请求方法 是 OPtions， 就放行
        if ("options".equalsIgnoreCase(request.getMethod())) {
            // 直接放行
            return true;
        }
        // 获取token  ？
        String token = request.getHeader("Authorization");
        System.out.println(token);
        if (token == null || token.trim().length() == 0 || JwtUtils.verifyToken(token) == false) {
            // 非法用户请求
            //  返回 正确 result 信息
            throw new BussinessException(ExType.InvalidToken, "身份认证失败！");
        }
        // 获取 用户名字
        String userName = JwtUtils.getClaimByName(token, "userName").asString();
        System.out.println("token username is " + userName);
        // 查询数据库
        User db = userService.queryByName(userName);
        // 清除 密码
        db.setPassword("");
        // 使用 request 的方法， 可以传递 信息
        request.setAttribute("user", db);
        // 返回结果
        return true;
    }
}
